<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const route = useRoute()

// 从路由参数获取ID
const props = defineProps<{ id?:number | string }>()
const id = computed(() => props.id || route.query.id)

const readClient = ReadClients[3]
const writeClient = WriteClients[3]
const loading = ref(false)
const data = ref<any>({
  creator: '李小南',
  createTime: '2025-09-17 20:00:27',
  updater: '李小南',
  updateTime: '2025-09-17 20:00:27',
})
const activeTab = ref('info')

function handleEdit(){ 
  router.push({ name: 'ProductEdit', query: { id: id.value, origin: 'detail' } })
}

async function handleDelete(){
  try{
    await ElMessageBox.confirm(`确认删除【${data.value?.productName}】吗？`, '提示', { type:'warning' })
    
    // 先删除产品记录
    await writeClient.get('/productwrite/api/Product/DeleteProduct', { params: { Id: props.id } })
    
    // 删除云端文件
    if (data.value?.image) {
      try {
        await writeClient.post('/productwrite/api/Upload/DeleteFile', null, { params: { url: data.value.image } })
      } catch (err) {
        console.warn('删除图片失败:', err)
      }
    }
    
    if (data.value?.attachment) {
      try {
        await writeClient.post('/productwrite/api/Upload/DeleteFile', null, { params: { url: data.value.attachment } })
      } catch (err) {
        console.warn('删除附件失败:', err)
      }
    }
    
    ElMessage.success('删除成功')
    router.push({ name: 'ProductInfo' })
  }catch{}
}

function handleEnable(){}
function handleDisable(){}

async function handlePrint(){
  try{ 
    // 使用 window.location.href 直接触发下载
    const downloadUrl = `${readClient.defaults.baseURL}/api/Product/ExportExcelProduct`
    window.location.href = downloadUrl
    ElMessage.success('导出任务已发起') 
  }catch{ 
    ElMessage.error('导出失败') 
  }
}

async function fetchDetail(){
  if(!id.value) return
  loading.value = true
  try{
    const res = await readClient.get('/productread/api/Product/GetProductById', { params:{ Id: id.value } })
    const payload = res?.data
    data.value = payload?.data || payload || null
  }catch{
    ElMessage.error('获取详情失败')
  }finally{
    loading.value = false
  }
}

onMounted(fetchDetail)
watch(()=>id.value, fetchDetail)
</script>

<template>
  <div class="detail-wrap" v-loading="loading">
    <!-- 顶部信息：单独卡片 -->
    <el-card class="top-card">
      <div class="card-header">
        <div class="title">{{ data?.productName || '产品详情' }} <span class="code">{{ data?.productNumber }}</span></div>
        <div class="meta">
          <span>创建人：{{ data?.creator || '-' }}</span>
          <span>创建时间：{{ data?.createTime || '-' }}</span>
          <span>更新人：{{ data?.updater || '-' }}</span>
          <span>更新时间：{{ data?.updateTime || '-' }}</span>
        </div>
        <div class="spacer"></div>
      </div>
      <div class="btn-bar">
        <el-button size="large" plain @click="handleEdit">编辑</el-button>
        <el-button size="large" plain @click="handleDelete">删除</el-button>
        <el-button size="large" plain @click="handleEnable">启用</el-button>
        <el-button size="large" plain @click="handleDisable">禁用</el-button>
        <el-button size="large" plain @click="handlePrint">打印</el-button>
      </div>
    </el-card>

    <!-- 内容卡片：基础信息 + 图片 + 附件（统一卡片内分块） -->
    <el-card class="content-card">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="产品信息" name="info">
      <div class="section">
        <div class="section-title"><el-tag size="small" effect="light">基础信息</el-tag></div>
        <el-descriptions :column="2" border size="large">
          <el-descriptions-item label="产品编号">{{ data?.productNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ data?.productName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ data?.specificationModel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ data?.unit || '-' }}</el-descriptions-item>
          <el-descriptions-item label="产品类型">{{ data?.productType || '-' }}</el-descriptions-item>
          <el-descriptions-item label="产品属性">{{ data?.productAttribute || '-' }}</el-descriptions-item>
          <el-descriptions-item label="产品分类">{{ data?.productClassification || '-' }}</el-descriptions-item>
          <el-descriptions-item label="启用状态">{{ (data?.activationStatus===true||data?.activationStatus===1||data?.activationStatus==='true')?'启用':'禁用' }}</el-descriptions-item>
          <el-descriptions-item label="有效日期">{{ data?.validDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="报警天数">提前{{ data?.alarmDays || '-' }}天报警</el-descriptions-item>
          <el-descriptions-item label="库存上限">{{ data?.maximumInventoryLevel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="库存下限">{{ data?.minimumInventoryLevel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="采购价格">{{ data?.purchasePrice || '-' }}</el-descriptions-item>
          <el-descriptions-item label="销售价格">{{ data?.salesPrice || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ data?.remarks || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <el-card class="section-card">
        <template #header>
          <div class="section-title"><el-tag size="small" effect="light">图片</el-tag></div>
        </template>
        <el-space wrap>
          <el-image v-for="(img,idx) in (data?.images || (data?.image ? [data?.image] : []))" :key="idx" :src="img" fit="cover" style="width:140px;height:140px;border-radius:6px;overflow:hidden" />
          <div v-if="!(data?.images?.length || data?.image)" class="empty-img">暂无图片</div>
        </el-space>
      </el-card>

      <el-card class="section-card">
        <template #header>
          <div class="section-title"><el-tag size="small" effect="light">附件</el-tag></div>
        </template>
        <div v-if="data?.attachments?.length">
          <div v-for="(att,idx) in data.attachments" :key="idx">
            <el-link type="primary" underline="hover" :href="att.url || att" target="_blank">{{ att.name || att }}</el-link>
          </div>
        </div>
        <div v-else-if="data?.attachment">
          <el-link type="primary" underline="hover" :href="data?.attachment" target="_blank">{{ data?.attachment }}</el-link>
        </div>
        <div v-else>暂无附件</div>
      </el-card>

      <el-card class="section-card">
        <div class="op-row">
          <el-button type="primary" size="large" @click="router.push({ name: 'ProductInfo' })">返回列表</el-button>
        </div>
      </el-card>
        </el-tab-pane>
        <el-tab-pane label="库存信息" name="stock">
          <div class="placeholder">暂无数据</div>
        </el-tab-pane>
        <el-tab-pane label="入库记录" name="inbound">
          <div class="placeholder">暂无数据</div>
        </el-tab-pane>
        <el-tab-pane label="出库记录" name="outbound">
          <div class="placeholder">暂无数据</div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
  
</template>

<style scoped>
/* 整体布局 */
.detail-wrap{ 
  display:flex; 
  flex-direction:column; 
  gap:20px; 
  padding:20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 顶部卡片样式 */
.top-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.top-card :deep(.el-card__body) {
  padding: 24px;
}

.card-header{ 
  display:flex; 
  flex-direction:column; 
  align-items:flex-start; 
  gap:12px; 
  margin-bottom: 20px;
}

.card-header .title{ 
  font-size:24px; 
  font-weight:600; 
  line-height:1.4; 
  color: #303133;
  margin: 0;
}

.card-header .title .code{ 
  font-size:16px; 
  font-weight:400; 
  color:#909399; 
  margin-left:12px; 
  background: #f5f7fa;
  padding: 4px 12px;
  border-radius: 4px;
}

.card-header .sub{ color:#666; }
.card-header .meta{ 
  display:flex; 
  gap:32px; 
  color:#606266; 
  font-size:14px; 
  flex-wrap: wrap;
}

.card-header .meta span {
  background: #f5f7fa;
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: 500;
}

.card-header .spacer{ flex:1; }
.back-btn{ align-self:flex-end; }

.btn-bar{ 
  display:flex; 
  gap:12px; 
  padding-top:16px; 
  flex-wrap: wrap;
}

.btn-bar .el-button {
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 6px;
}

/* 内容卡片样式 */
.content-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.content-card :deep(.el-card__body) {
  padding: 0;
}

/* 标签页样式 */
.detail-tabs :deep(.el-tabs__header) {
  margin: 0;
  background: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
  color: #606266;
  padding: 16px 24px;
  border: none;
}

.detail-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  background: white;
  border-radius: 6px 6px 0 0;
}

.detail-tabs :deep(.el-tabs__item:hover) {
  color: #409eff;
}

.detail-tabs :deep(.el-tabs__content) {
  padding: 24px;
}

/* 基础信息样式 */
.section{ 
  border: 1px solid #ebeef5;
  border-radius: 8px; 
  padding: 24px; 
  margin-top: 0;
  background: white;
}

.section-title{ 
  text-align:center; 
  margin:0 0 20px 0; 
}

.section-title :deep(.el-tag){ 
  border-radius: 4px; 
  font-weight: 500;
  padding: 4px 12px;
  font-size: 12px;
}

.section :deep(.el-descriptions__header) {
  margin-bottom: 20px;
}

.section :deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section :deep(.el-descriptions__body) {
  background: #fafafa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.section :deep(.el-descriptions__cell) {
  border: 1px solid #ebeef5;
  padding: 16px 20px;
}

.section :deep(.el-descriptions__label) {
  background: #f5f7fa;
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.section :deep(.el-descriptions__content) {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}

/* 底部按钮样式 */
.section-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  margin-top: 20px;
}

.section-card :deep(.el-card__body) {
  padding: 24px;
}

.op-row{ 
  display:flex; 
  justify-content:center; 
  gap:16px; 
}

.op-row .el-button {
  font-weight: 500;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
}

/* 占位符样式 */
.placeholder{ 
  color:#999; 
  padding:40px 0; 
  text-align: center;
  font-size: 14px;
  background: #f5f7fa;
  border-radius: 6px;
  margin: 20px 0;
}

/* 图片样式 */
.empty-img{ 
  width:140px; 
  height:140px; 
  display:flex; 
  align-items:center; 
  justify-content:center; 
  color:#999; 
  background:#f8f9fb; 
  border:1px dashed #e5e7eb; 
  border-radius:6px; 
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-wrap {
    padding: 16px;
    gap: 16px;
  }
  
  .card-header .meta {
    gap: 20px;
    flex-direction: column;
  }
  
  .btn-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .op-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .detail-tabs :deep(.el-tabs__content) {
    padding: 16px;
  }
  
  .section {
    padding: 16px;
  }
}

/* 卡片按钮更大间隔 */
.btn-bar .el-button{ min-width:80px; }

/* 基础信息使用 Element Plus Descriptions 组件 */

/* 图片略放大 */
.empty-img{ width:160px; height:160px; }

.op-row{ display:flex; justify-content:center; }
</style>


